package src.D_WinSock;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class D04_UDP_MengMemg_Chat implements Runnable{
    DatagramSocket socket = null;
    private int iport;
    private String msgName;

    public D04_UDP_MengMemg_Chat(int iport, String msgName) {
        this.iport = iport;
        this.msgName = msgName;
        // 1、开放端口
        try {
            socket = new DatagramSocket(iport);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            // 2、接收数据包
            while (true){
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
                socket.receive(packet); // 阻塞式接收
                System.out.println(this.msgName+"："+new String(packet.getData(),0,packet.getLength()));
                if (new String(packet.getData(),0,packet.getLength()).equals("close")) break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null){
                // 3、关闭流
                socket.close();
            }
        }
    }
}

class Test02{
    public static void main(String[] args) {
        new Thread(new D04_UDP_LeLe_Chat(6666,"localhost",7777)).start();
        new Thread(new D04_UDP_MengMemg_Chat(9999,"蜡笔小裂")).start();
    }
}